/*
 * SFTPSessionHandler.h
 *
 *  Created on: Apr 6, 2011
 *      Author: sms103
 */

#ifndef SFTPSESSIONHANDLER_H_
#define SFTPSESSIONHANDLER_H_
/* Handles the server side of an SFTP session. Initializes, waits for a
 * data connection to be established, then waits for commands from the client.
 * Every object runs in its own thread.
 */

class SFTPSessionHandler;

#include <pthread.h>
#include <sys/time.h>
#include <stdint.h>
#include <time.h>
#include "SFTPServer.h"
#include "../networklib/SFTPConnection.h"
#include "../networklib/SFTPMessage.h"
#include "../networklib/FileTransporter.h"

//after a ctrl connection is established, we wait this long for a data connection,
//then give up and kill the ctrl conn. This is in SECONDS
#define DATA_CONN_WAIT_TIMEOUT 10

class SFTPSessionHandler {
public:
	SFTPSessionHandler(SFTPServer *sftpServer,SFTPConnection *conn);


	/* Sets the data connection for this session handler. Signals the handler's
	 * thread that the data conn is ready. */
	void setDataConn(SFTPConnection *conn);

	virtual ~SFTPSessionHandler();

private:
	SFTPServer *sftpServer;
	uint32_t sessionID;

	SFTPConnection *ctrlConnection;
	SFTPConnection *dataConnection;

	FileTransporter *fileTransporter;

	pthread_mutex_t sessionMutex;
	pthread_cond_t sessionCond;
	pthread_t sessionThread;

	/* Waits the specified timeout in milliseconds for a data connection to be
	 * established. returns true if a data conn was establisged, false if we timed out.
	 * Timeout of zero means return immediately whether dataConn is set or not.
	 * Timeout less than zero means infinite wait.
	 */
	bool waitForDataConn(int timeout);

	bool handlePut(string filename);
	bool handleGet(string filename);
	bool handleLis(string pathname);

	static void * runSessionThread(void *p);

};

#endif /* SFTPSESSIONHANDLER_H_ */
